package com.nuoniu.sibanyun.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.annotation.SqlParser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.microsoft.schemas.office.visio.x2012.main.CellType;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.common.lang.StringUtils;
import com.nuoniu.sibanyun.entity.SysCompany;
import com.nuoniu.sibanyun.entity.SysEmployee;
import com.nuoniu.sibanyun.entity.vo.SysEmployeeSimpleVo;
import com.nuoniu.sibanyun.mapper.SysEmployeeMapper;
import com.nuoniu.sibanyun.service.ISysCompanyService;
import com.nuoniu.sibanyun.service.ISysEmployeeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import com.nuoniu.sibanyun.utils.ExcelUtils;
import com.nuoniu.sibanyun.utils.SendSmsUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.spring.web.json.Json;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.*;


//*
// * <p>
// * 员工表 服务实现类
// * </p>
// *
// * @author baiqiang
// * @since 2020-05-29


@Service
public class SysEmployeeServiceImpl extends ServiceImpl<SysEmployeeMapper, SysEmployee> implements ISysEmployeeService {

    @Autowired
    private SysEmployeeMapper employeeMapper;
    @Autowired
    private ISysCompanyService companyService;

    public static String SignName = "四班云";

    @Override
    public SysEmployee getByUserId(Long id) {
        return employeeMapper.getByUser(id);
    }

    @Override
    public Page<SysEmployeeSimpleVo> pageSysEmployeeSimpleVo(Page page,Integer officeId,String searchKey) {
        UserInfo userInfo = UserThreadLocal.get();
//        if (null == officeId) throw new NuoNiuException("请选择部门");
        Page<SysEmployeeSimpleVo> sysEmployeeSimpleVoPage = baseMapper.pageSysEmployeeSimpleVo(page, userInfo.getCompanyId(), officeId,searchKey);
        return sysEmployeeSimpleVoPage;
    }

    @Override
    public Map importEmployee(MultipartFile file) throws IOException, NoSuchFieldException {
        UserInfo userInfo = UserThreadLocal.get();
        //成功个数
        int successNum = 0;
        //失败个数
        int failureNum = 0;
        //失败原因
        List<String> failCauseList = new ArrayList<>();
        //失败数据
        List<List<String>> failDataList = new ArrayList<>();
        //员工数据
        List<SysEmployee> employeeList = new ArrayList<>();

        //员工手机号标记
        Map<String, SysEmployee> employeeMap = new HashMap();
        String[] phoneArr = baseMapper.getPhoneByCompanyId(userInfo.getCompanyId());
        String[] empFiled = {"empNo", "empName", "userPhone", "empNameEn", "nation", "email", "residentialAddress"};
        Workbook wb;
        boolean isExcel2003 = true;

        if (file.getOriginalFilename().matches("^.+\\.(?i)(xlsx)$")) {
            isExcel2003 = false;
        }

        //解析excel
        InputStream is = file.getInputStream();
        if (isExcel2003) {
            wb = new HSSFWorkbook(is);
        } else {
            wb = new XSSFWorkbook(is);
        }

        Sheet sheet = wb.getSheetAt(0);
        for (int r = 1; r <= sheet.getLastRowNum(); r++) { //循环excel行读取数据
            List<String> cellData = new ArrayList<>();
            SysEmployee employee = new SysEmployee(); //供应商数据
            Row row = sheet.getRow(r);
            for(int i=0; i<empFiled.length; i++) {
                if (row.getCell(i) == null) {
                    cellData.add("");
                    continue;
                }

                row.getCell(i).setCellType(CellType.GREATER_THAN);
                String cellValue = (row.getCell(i).getStringCellValue() + "").trim();
                cellData.add(cellValue);

                Class crmCompanyClass = employee.getClass();
                Field f = crmCompanyClass.getDeclaredField(empFiled[i]);
                f.setAccessible(true);
                try {
                    f.set(employee, cellValue);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }

            if(employee == null || StringUtils.isBlank(employee.getEmployeeName())) { //员工名称不能为空
                failCauseList.add("第" + (r + 1) + "行:" + "员工名称不能为空");
                failDataList.add(cellData);
                failureNum ++;
                continue;
            }

            if(StringUtils.isBlank(employee.getPhoneNumber())) {
                failCauseList.add("第" + (r + 1) + "行:" + "手机号不能为空");
                failDataList.add(cellData);
                failureNum ++;
                continue;
            }

            if(Arrays.asList(phoneArr).contains(employee.getPhoneNumber()) || employeeMap.get(employee.getPhoneNumber()) != null) {
                failCauseList.add("第" + (r + 1) + "行:" + "手机号已存在");
                failDataList.add(cellData);
                failureNum ++;
                continue;
            }

            employeeMap.put(employee.getPhoneNumber(), employee);
            employee.setTenantId(userInfo.getCompanyId().longValue());
            employee.setTenantName(userInfo.getCompanyName());
            employeeList.add(employee);
            successNum++;
        }

        if (employeeList != null && employeeList.size() > 0) { //批量插入数据
            this.saveBatch(employeeList);
        }

        String[] excelField = {"员工工号", "员工姓名", "手机号", "英文名", "民族", "邮箱", "居住地址"};
        Map result = new HashMap();
        result.put("failNum", failureNum);
        result.put("successNum", successNum);
        result.put("failCause", failCauseList);
        result.put("failData", failDataList);
        result.put("excelField", excelField);
        return result;
    }
//todo 目前前端还未实现
    @Override
    public Page<SysEmployee> pageList(Page page) {
        UserInfo userInfo = UserThreadLocal.get();
        QueryWrapper<SysEmployee> wrapper = new QueryWrapper<>();
        Integer companyId = userInfo.getCompanyId();
        wrapper.eq("company_id",companyId);
        return page(page,wrapper);
    }

    @Override
    public void importTemplate(HttpServletResponse response) {
        String fileName = "导入员工模板.xls";
        String[] data = {"001", "小明", "13320371111", "xm", "汉族", "xx@qq.com", "重庆市江北区"};
        Object[] title = {"员工工号", "员工姓名", "手机号", "英文名", "民族", "邮箱", "居住地址"};
        ExcelUtils.export(title,  fileName, data, response);
    }

    @Override
    public void delete(Long id) {
        SysEmployee employee = getById(id);
        if(employee != null && employee.getTenantId() != null) {
            throw new NuoNiuException("已入职,不能删除");
        }
        removeById(id);
    }

    @Override
    public void inviteToRegister(String[] userPhones) {
        List<String> signNameList = new ArrayList<>();
        List<Map<String, String>> paramList = new ArrayList<>();
        UserInfo userInfo = UserThreadLocal.get();
        SysCompany company = companyService.getById(userInfo.getCompanyId());
        if(company != null) {
            for(String userPhone : userPhones) {
                SysEmployee employee = baseMapper.getByUserPhone(userPhone);
                if(employee != null && employee.getTenantId() == null) {
                    Map<String, String> param = new HashMap<>();
                    signNameList.add(SignName);
                    param.put("code", employee.getId().toString());
                    paramList.add(param);
                }
            }

            if(signNameList.size() > 0) {
                SendSmsUtils.sendEmpSms(JSON.toJSONString(signNameList), JSON.toJSONString(paramList), JSON.toJSONString(userPhones));
            }
        }
    }

}
